package com.ruoyi.common.utils;

import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;

import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;

/**
 * csv文件工具类
 */
public class CsvUtils {

    public static boolean writerList(List<String> dataList, String filePath) {
        try {
            CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(new FileOutputStream(filePath, true), "GBK"));
//属性名称
            // 遍历 List<Map> 数据
            for (String str : dataList) {
                // 将 Map 转换为一行 CSV 数据
                String[] csvData = {str};
                // 将 CSV 数据写入文件
                csvWriter.writeNext(csvData);
            }
            // 刷新 CSVWriter 对象，确保数据写入文件
            csvWriter.flush();
            // 关闭 CSVWriter 对象
            csvWriter.close();
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 写入List<map<String, Object> 到csv文件
     *
     * @param dataList 数据
     * @param filePath csv文件路径
     */
    public static boolean writer(List<Map<String, Object>> dataList, String filePath) {
        try {
            CSVWriter csvWriter = new CSVWriter(new OutputStreamWriter(new FileOutputStream(filePath, true), "GBK"));
//属性名称
            if (!dataList.isEmpty()) {
                String[] csvData = new String[dataList.get(0).keySet().size()];
                int index = 0;
                for (String key : dataList.get(0).keySet()) {
                    csvData[index++] = ObjectUtils.ObjToString(key);
                }
                csvWriter.writeNext(csvData);
            }
//数据
            // 遍历 List<Map> 数据
            for (Map<String, Object> map : dataList) {
                // 将 Map 转换为一行 CSV 数据
                String[] csvData = new String[map.size()];
                int index = 0;
                for (String key : map.keySet()) {
                    csvData[index++] = ObjectUtils.ObjToString(map.get(key));
                }
                // 将 CSV 数据写入文件
                csvWriter.writeNext(csvData);
            }
            // 刷新 CSVWriter 对象，确保数据写入文件
            csvWriter.flush();
            // 关闭 CSVWriter 对象
            csvWriter.close();
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return false;
        }
        return true;
    }

    /**
     * 读取csv文件写入List<String>
     */
    public static List<String> readerList(String filePath) {
        List<String> dataList = new ArrayList<>();
        CSVReader csvReader = null;
        try {
            csvReader = new CSVReader(new InputStreamReader(Files.newInputStream(Paths.get(filePath)), "GBK"));
            String[] nextRecord;
            while ((nextRecord = csvReader.readNext()) != null) {
                dataList.add(nextRecord[0]);
            }
            csvReader.close();
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return null;
        }
        return dataList;
    }

    /**
     * 读取csv文件写入List<map<String, Object>
     */
    public static List<Map<String, Object>> reader(String filePath) {
        List<Map<String, Object>> dataList = new ArrayList<>();
        CSVReader csvReader = null;
        try {
            csvReader = new CSVReader(new InputStreamReader(Files.newInputStream(Paths.get(filePath)), "GBK"));
            String[] nextRecord;

            List<String> nameList = null;
            while ((nextRecord = csvReader.readNext()) != null) {
                if (nameList == null) {
                    nameList = new ArrayList<>(Arrays.asList(nextRecord));
                } else {
                    Map<String, Object> map = new HashMap<>();
                    for (int i = 0; i < nextRecord.length; i++) {
                        map.put(nameList.get(i), nextRecord[i]);
                    }
                    dataList.add(map);
                }
            }
            csvReader.close();
        } catch (Exception e) {
            System.err.println(e.getMessage());
            return null;
        }
        return dataList;
    }
}
